/*
 * @Author: yangfan 1437446666@qq.com
 * @Date: 2023-02-27 11:49:28
 * @LastEditors: yangfan 1437446666@qq.com
 * @LastEditTime: 2023-03-10 08:42:47
 * @FilePath: \s_2006A_shixun\src\router\index.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import {
  createRouter,
  createWebHistory,
  RouteRecordRaw,
  createWebHashHistory
} from 'vue-router'
import Cookie from 'js-cookie'
import store from '../store/index'
import RouterTypr from '../router/userRouter'
//过滤路由表的方法
import { filterRouter } from '@/utils/filterRouter'
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/login'
  },
  //登录
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login.vue')
  },
  {
    path: '/md-editor',
    name: 'md-editor',
    component: () => import('../views/mdeditor.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes
})
// 白名单
const whiteList = ['/login']
router.beforeEach((to, from, next) => {
  const token = Cookie.get('token')
  //判断是否是白名单
  if (whiteList.includes(to.path)) {
    //继续执行
    next()
  } else {
    //判断是否存在tokenstore.state.user.role
    if (token) {
      //判断是否存在路由表
      // console.log(store.state.Routers.length)
      if (store.state.Routers.length <= 0) {
        // console.log('可以动态路由', 111)
        // const { renderRouter } = JSON.parse(sessionStorage.getItem('vuex'))
        // console.log(JSON.parse(sessionStorage.getItem('vuex')))
        // renderRouter.forEach((value) => {
        //   console.log(value)
        //   router.addRoute(value)
        // })
        store.dispatch('getRouters', 'visitor')
        next({ ...to, replace: true })
        // store.commit('set_state', { key: 'Routers', data: RouterTypr })
      } else {
        next()
      }
    } else {
      //跳转登录页
      next('/login')
    }
  }
})
export default router
